﻿Imports System.Web.Services
Imports System.Net
Imports System.IO


Public Class Downloader

    Sub DownloadTrades()
        Try

            Dim sCreds As String = My.Settings.sInsitution & "." & My.Settings.sUserID
            Dim wsDL As New GTSSWebService.FxWebService

            If My.Settings.bConnectLTS Then
                wsDL.Url = "http://" & My.Settings.sLTSIP & "/gtss/service/FxWebService"
            Else
                wsDL.Url = My.Settings.sGTSSURL.Replace("/FileWebService", "/FxWebService")
            End If


            wsDL.Credentials = New System.Net.NetworkCredential(sCreds, My.Settings.sPW)
            wsDL.CookieContainer = New System.Net.CookieContainer

            Dim wsReq As New GTSSWebService.GetTradesByDateRequestType
            With wsReq

                .whichDates = New GTSSWebService.WhichDatesType

                Dim tsAfterMidnight As New TimeSpan(0, 0, 1)
                Dim tsBeforeMidnight As New TimeSpan(0, 0, -1)

                If My.Settings.bGTSSDLUseLastRun Then
                    Dim dtNow As Date = Now()
                    Dim dtThen As Date = My.Settings.dtLastDL
                    My.Settings.dtLastDL = Now()
                    My.Settings.Save()
                    'perhaps build in several second delay to allow uploaded trades to process
                    .whichDates.startDate = Date.Now.AddHours(-6)
                    .whichDates.endDate = dtNow
                Else
                    If (Not My.Settings.iGTSSDLDaysPrior = 0 AndAlso Not My.Settings.iGTSSDLDaysAfter = 0) Then
                        If My.Settings.iGTSSDLDaysPrior = 0 Then My.Settings.iGTSSDLDaysPrior += 1
                        If My.Settings.iGTSSDLDaysAfter = 0 Then My.Settings.iGTSSDLDaysAfter += 1
                    End If
                    .whichDates.startDate = Today.AddDays(My.Settings.iGTSSDLDaysPrior.ToString * -1).Add(tsAfterMidnight) 'to string to handle dec oddness
                    .whichDates.endDate = Today.AddDays(My.Settings.iGTSSDLDaysAfter.ToString).Add(tsBeforeMidnight)
                End If

                .whichDates.endDateSpecified = True
                .whichDates.dateFilter = My.Settings.sGTSSDLDateFilter
                .whoseTrades = New GTSSWebService.WhoseTradesType
                .whoseTrades.includeDirectTrades = True
                .whoseTrades.includeDirectTradesSpecified = True
                .whoseTrades.includeThirdPartyTrades = True
                .whoseTrades.includeThirdPartyTradesSpecified = True
                .whoseTrades.oursVersusTheirs = "EITHER"
                .includeSettlementDetails = True
                .includeSettlementDetailsSpecified = True
                .statusFilter = My.Settings.sGTSSDLStatusFilter
                '.includeMatchedTradeDetails = False
                '.includeMatchedTradeDetailsSpecified = True
            End With

            Dim wsResp As GTSSWebService.GetTradesByDateResponseType

            wsResp = wsDL.GetTradesByDate(wsReq)

            If My.Settings.sFileUploadType = "CRD" AndAlso My.Settings.bCRDGTSSDownload Then
                'TODO CRD update
            Else
                WriteDLFile(wsResp)
            End If

        Catch ex As Exception
            Logger.ErrorLog(ex, "GTSS Download")
            Exit Sub
        End Try

    End Sub

    Private Sub WriteDLFile(ByVal wsResp As GTSSWebService.GetTradesByDateResponseType)

        Try
            Dim bAppend As Boolean = False
            Dim sD As String
            Dim sHeader As String = String.Empty

            Select Case My.Settings.sGTSSDLDelim.ToLower
                Case "tab"
                    sD = vbTab
                Case "comma"
                    sD = ","
                Case "semicolon"
                    sD = ";"
            End Select

            If wsResp.trades.Length = 0 Then Logger.MsgLog("No trades to download with selected criteria")

            If Not Directory.Exists(My.Settings.sGTSSDLDir) Then Directory.CreateDirectory(My.Settings.sGTSSDLDir)

            If My.Settings.sGTSSDLFileName = String.Empty AndAlso (My.Settings.sGTSSDLOutputType.ToLower = "append" OrElse _
            My.Settings.sGTSSDLOutputType.ToLower = "overwrite") Then
                Logger.ErrorLog("File name must be specified for 'Append' and 'Overwrite' output options.")
                Exit Sub
            ElseIf My.Settings.sGTSSDLFileName = String.Empty AndAlso My.Settings.sGTSSDLOutputType.ToLower = "new file" Then
                My.Settings.sGTSSDLFileName = "GTSSDL" & String.Format("{0:MMddyyhhmmss", Now())
            ElseIf My.Settings.sGTSSDLOutputType.ToLower = String.Empty Then
                Logger.ErrorLog("File output for download must be selected.")
                Exit Sub
            Else
                If My.Settings.sGTSSDLOutputType.ToLower = "new file" Then
                    My.Settings.sGTSSDLFileName = My.Settings.sGTSSDLFileName & String.Format("{0:MMddyyhhmmss", Now()) & My.Settings.sGTSSDLFileExt
                Else
                    bAppend = True
                End If
            End If
            My.Settings.sGTSSDLFileName = Path.Combine(My.Settings.sGTSSDLDir, My.Settings.sGTSSDLFileName & My.Settings.sGTSSDLFileExt)


            Dim drFields As dsDLFields.DLFieldsRow() = DirectCast(My.Settings.DLFields(0).Select("Selected = True"), dsDLFields.DLFieldsRow())


            If drFields.Count > 0 Then
                For Each drField As dsDLFields.DLFieldsRow In drFields
                    'print header row   
                    sHeader = sHeader & drField.FieldName & sD
                Next
                sHeader = Left(sHeader, sHeader.Length - 1) 'trim last add of delimeter
            Else
                Logger.ErrorLog("No fields selected for download file.  Please select at least one field and re-run.")
            End If


            Dim PrintList As New Generic.List(Of String)
            Using swDL As New StreamWriter(My.Settings.sGTSSDLFileName, bAppend)
                If My.Settings.bGTSSDLUseHeader AndAlso ((Not My.Settings.sGTSSDLOutputType.ToLower = "new file" AndAlso _
                Not File.Exists(My.Settings.sGTSSDLFileName) OrElse My.Settings.sGTSSDLOutputType.ToLower = "new file")) _
                Then swDL.WriteLine(sHeader)

                For Each dlTrade As GTSSWebService.FxTradeDownloadType In wsResp.trades
                    Dim wsrtTrade As New WSResponseTrade(dlTrade)
                    PrintList.Clear()

                    If My.Settings.bGTSSDLDayIssue Then
                        wsrtTrade.TradeDate = wsrtTrade.TradeDate.AddDays(1)
                        wsrtTrade.SettleDate = wsrtTrade.SettleDate.AddDays(1)
                    End If


                    For Each drField As dsDLFields.DLFieldsRow In drFields
                        Select Case drField.FieldName
                            Case "Counterparty Name"
                                PrintList.Add(wsrtTrade.CPName)
                            Case "Counterparty BIC"
                                PrintList.Add(wsrtTrade.CPBIC)
                            Case "Custodian BIC"
                                PrintList.Add(wsrtTrade.CustBIC)
                            Case "Custodian Name"
                                PrintList.Add(wsrtTrade.CustName)
                            Case "Fund Legal Name"
                                PrintList.Add(wsrtTrade.FundLegalName)
                            Case "Fund Display Code"
                                PrintList.Add(wsrtTrade.FundDisplayCode)
                            Case "Fund"
                                PrintList.Add(wsrtTrade.Fund)
                            Case "Global Link ID"
                                PrintList.Add(wsrtTrade.GLID)
                            Case "Owner BIC"
                                PrintList.Add(wsrtTrade.OwnerBIC)
                            Case "Owner Name"
                                PrintList.Add(wsrtTrade.OwnerName)
                            Case "Side"
                                PrintList.Add(wsrtTrade.Side)
                            Case "Amount Bought"
                                PrintList.Add(wsrtTrade.AmtBought)
                            Case "Amount Sold"
                                PrintList.Add(wsrtTrade.AmtSold)
                            Case "Currency Bought"
                                PrintList.Add(wsrtTrade.CCYBought)
                            Case "Currency Sold"
                                PrintList.Add(wsrtTrade.CCYSold)
                            Case "NDF Fixing Date"
                                If wsrtTrade.FixingDate = #12:00:00 AM# Then ' response has #12:00:00 AM# as the null value so changed to "" in the file
                                    PrintList.Add("")
                                Else
                                    PrintList.Add(Trade.ConvertDate(wsrtTrade.FixingDate, My.Settings.sGTSSDLDateFormat))
                                End If
                            Case "NDF Fixing Date Specified"
                                PrintList.Add(wsrtTrade.FixingDateSpecified)
                            Case "Rate"
                                PrintList.Add(wsrtTrade.Rate)
                            Case "Value Date"
                                PrintList.Add(Trade.ConvertDate(wsrtTrade.SettleDate, My.Settings.sGTSSDLDateFormat))
                            Case "Trade Date"
                                PrintList.Add(Trade.ConvertDate(wsrtTrade.TradeDate, My.Settings.sGTSSDLDateFormat))
                            Case "Transaction ID"
                                PrintList.Add(wsrtTrade.TransID)
                            Case "Affirmation"
                                PrintList.Add(wsrtTrade.Affirmation)
                            Case "Audit Time"
                                PrintList.Add(Trade.ConvertDate(wsrtTrade.AuditTime, My.Settings.sGTSSDLDateFormat))
                            Case "Comments"
                                PrintList.Add(wsrtTrade.Comments)
                            Case "Created Time"
                                PrintList.Add(Trade.ConvertDate(wsrtTrade.CreatedTime, My.Settings.sGTSSDLDateFormat))
                            Case "Match Description"
                                PrintList.Add(wsrtTrade.MatchDescription)
                            Case "Match GLID"
                                PrintList.Add(wsrtTrade.MatchGLID)
                            Case "Match GLID Specified"
                                PrintList.Add(wsrtTrade.MatchFieldSpecified)
                            Case "SIBought"
                                PrintList.Add(wsrtTrade.SIBought)
                            Case "SISold"
                                PrintList.Add(wsrtTrade.SISold)
                            Case "Trade Status"
                                PrintList.Add(wsrtTrade.Status)
                            Case "Buy Delivery Agent"
                                PrintList.Add(wsrtTrade.BuyDelivAgent.Replace(vbCrLf, "|"))
                            Case "Buy Intermediary"
                                PrintList.Add(wsrtTrade.BuyInter.Replace(vbCrLf, "|"))
                            Case "Buy Receiving Agent"
                                PrintList.Add(wsrtTrade.BuyRecAgent.Replace(vbCrLf, "|"))
                            Case "Common Reference ID"
                                PrintList.Add(wsrtTrade.CommRefID)
                            Case "Sell Beneficiary"
                                PrintList.Add(wsrtTrade.SellBeneInst.Replace(vbCrLf, "|"))
                            Case "Sell Delivery Agent"
                                PrintList.Add(wsrtTrade.SellDelivAgent.Replace(vbCrLf, "|"))
                            Case "Sell Intermediary"
                                PrintList.Add(wsrtTrade.SellInter.Replace(vbCrLf, "|"))
                            Case "Sell Receiving Agent"
                                PrintList.Add(wsrtTrade.SellRecAgent.Replace(vbCrLf, "|"))
                            Case "Sender to Receiver Info"
                                PrintList.Add(wsrtTrade.SenderToRecInfo.Replace(vbCrLf, "|"))

                        End Select
                    Next
                    swDL.WriteLine(PrintRow(PrintList, sD))
                Next



            End Using

        Catch ex As Exception
            Logger.ErrorLog(ex, "GTSS Download")
            Exit Sub
        End Try
    End Sub

    Private Function PrintRow(ByVal Trade As Generic.List(Of String), ByVal sDelimiter As String) As String
        ' creates a string with commas based on the generic list populated in the select statment
        ' this string is what is printed out by the WriteDownload sub
        Dim iCounter As Integer = 0
        PrintRow = String.Empty

        For Each sItem As String In Trade
            If iCounter = 0 Then
                PrintRow = PrintRow & sItem
            Else
                PrintRow = PrintRow & sDelimiter & sItem
            End If
            iCounter += 1

        Next

    End Function

End Class
